//
//  WmcLocalAlbumDBManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/25.
//

import Foundation
import UIKit
import YPBedrock

// MARK: - [WmcLocalAlbumDBManager]

// @available(*, unavailable)
public struct WmcLocalAlbumDBManager: WmcDBProtocol {
    /// 图片模型
    struct ImageModel {
        var id: Int
        var thumbnailImagePath: String
        var originlImagePath: String
        var shootTime: Date
        var userId: Int
        var saveTime: Date
        var changeTime: Date
        var groupDay: Int
        var watermarkInfo: String?
    }

    // Internal

    /// 表名
    static var tableName: String = "local_album"

    /// 时间格式
    static var dateFormat: String = "yyyy-MM-dd hh:mm:ss"

    /// 图片文件夹名
    static var localAlbumFolderName: String = "WmcLocalAlbum"

    /// 文件管理器
    static var fileManager: FileManager = .default

    /// 表头数据列
    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(), // 主键
            .varchar(name: "original_image"), // 原图地址
            .varchar(name: "thumbnail_image"), // 缩略图地址
            .integer(name: "user_id"), // 用户信息
            .date(name: "shoot_time"), // 拍摄时间
            .date(name: "save_time"), // 存储时间
            .date(name: "change_time"), // 修改时间
            .integer(name: "group_day"), // 以天为分组
            .varchar(name: "watermark_info"), // json格式的字符串水印数据
        ]
    }

    /// 插入图片数据
    /// - Parameters:
    ///   - image: 图片
    ///   - watermarkInfo: 水印信息
    ///   - shootTime: 拍摄时间
    ///   - saveDate: 存储时间
    ///   - resultBlock: 结果
    static func insertImage(_ image: UIImage,
                            watermarkInfo: String,
                            shootTime: Date,
                            saveDate: Date = .init(),
                            resultBlock: YPBlock.OneParam<(UIImage, String, String)?>? = nil)
    {
        // 图片数据处理
        guard let originalImageData = image.yp.pngData,
              let thumbnailImageData = image.yp.set(squareMode:.center)?
              .yp.setScale(ratio: 0.2)?
              .yp.pngData else { return }
        // 用户信息
        var userId: Int = 0
        if let _userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !_userId.isEmpty {
            userId = _userId.yp.int
        }
        // 图片存文件夹
        let datePath = "\(saveDate.yp.year)/\(saveDate.yp.month)/\(saveDate.yp.day)"
        let groupFolder = localAlbumFolderName.yp.appendPathComponent(datePath)
        // 图片相对路径
        let originFilePath = groupFolder.yp.appendPathComponent("origin_\(image.hashValue)")
        let thumbFilePath = groupFolder.yp.appendPathComponent("thumb_\(image.hashValue)")
        // 建好文件夹
        let createPath = YPSystem.Documents.Path.yp.appendPathComponent(groupFolder)
        try? fileManager.yp.createDirectory(createPath)
        // 写入文件
        let originWritePath = YPSystem.Documents.Path.yp.appendPathComponent(originFilePath)
        let thumbWritePath = YPSystem.Documents.Path.yp.appendPathComponent(thumbFilePath)
        // 写入图片
        try? originalImageData.write(to: originWritePath.yp.fileUrl)
        try? thumbnailImageData.write(to: thumbWritePath.yp.fileUrl)
        // 日期数据处理
        let shootTimeInterval = shootTime.timeIntervalSince1970.yp.int
        let saveTimeInterval = (saveDate.timeIntervalSince1970).yp.int
        let groupDay = groupFolder.yp.replacing("/", with: "").yp.int
        // 调用数据库
        WmcDBManager.shared.insertData(tableName: Self.tableName, insertData: [
            .init(column: dataType[1], value: originFilePath),
            .init(column: dataType[2], value: thumbFilePath),
            .init(column: dataType[3], value: userId),
            .init(column: dataType[4], value: shootTimeInterval),
            .init(column: dataType[5], value: saveTimeInterval),
            .init(column: dataType[6], value: saveTimeInterval),
            .init(column: dataType[7], value: groupDay),
            .init(column: dataType[8], value: watermarkInfo),
        ]) { result in
            if result {
                resultBlock?((image, originFilePath, thumbFilePath))
            } else {
                resultBlock?(nil)
            }
        }
    }

    /// 读取搜索数据
    /// - Parameters:
    ///   - page: 分页
    ///   - pageSize: 分页大小
    ///   - resultBlock: 返回Block
    static func searchImageData(page: Int = 1,
                                pageSize: Int = 200,
                                resultBlock: YPBlock.OneParam<[ImageModel]>? = nil)
    {
        WmcDBManager.shared.searchData(tableName: tableName, page: page, pageSize: pageSize, isDesc: true) { dicList in
            var imageList: [ImageModel] = []
            dicList.forEach { dic in
                if let id = dic[dataType[0].name] as? Int,
                   let originlImagePath = dic[dataType[1].name] as? String,
                   let thumbnail_image_path = dic[dataType[2].name] as? String,
                   let user_id = dic[dataType[3].name] as? Int,
                   let shoot_time = dic[dataType[4].name] as? Int,
                   let save_time = dic[dataType[5].name] as? Int,
                   let change_time = dic[dataType[6].name] as? Int,
                   let groupDay = dic[dataType[7].name] as? Int
                {
                    // 因为是可选
                    let watermark_info = dic[dataType[8].name] as? String
                    // 获取当前路径
                    let shootTime = shoot_time.yp.secondsDate
                    let saveTime = save_time.yp.secondsDate
                    let changeTime = change_time.yp.secondsDate
                    let model = ImageModel(id: id,
                                           thumbnailImagePath: thumbnail_image_path,
                                           originlImagePath: originlImagePath,
                                           shootTime: shootTime,
                                           userId: user_id,
                                           saveTime: saveTime,
                                           changeTime: changeTime,
                                           groupDay: groupDay,
                                           watermarkInfo: watermark_info)
                    imageList.append(model)
                }
            }
            resultBlock?(imageList)
        }
    }

    /// 查询原图
    /// - Parameters:
    ///   - id: id
    ///   - resultBlock: 结果
    static func searchOriginImage(id: Int,
                                  resultBlock: YPBlock.OneParam<UIImage?>? = nil)
    {
        WmcDBManager.shared.searchData(tableName: tableName, id: id) { dic in
            // 解析
            if let origin_image_path = dic?[dataType[1].name] as? String {
                // 获取当前路径
                let originPath = YPSystem.Documents.Path.yp.appendPathComponent(origin_image_path)
                if let originImage = UIImage(contentsOfFile: originPath) {
                    resultBlock?(originImage)
                }
            }
        }
    }

    /// 删除图片
    /// - Parameters:
    ///   - id: id
    ///   - resultBlock: 结果
    static func deleteImage(id: Int,
                            resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        WmcDBManager.shared.deleteData(tableName: tableName, id: id, resultBlock: resultBlock)
    }
}
